<!-- 积分展示 -->
<!-- 奖励图片生成 -->
<!-- 历史奖励展示 --> 

<template>
  <view class="rewards-page">
    <!-- 顶部导航 -->
    <view class="nav-bar">
      <text class="title">奖励中心</text>
    </view>

    <!-- 积分卡片 -->
    <view class="points-card">
      <view class="header">
        <text>我的积分</text>
        <button class="rules-btn" @click="showRules">
          <text class="iconfont icon-info"></text>
          积分规则
        </button>
      </view>
      <view class="points">{{ pointsInfo.totalPoints }}</view>
      <view class="info">
        <text>今日已获得: {{ pointsInfo.todayPoints }}积分</text>
        <text>今日还可获得: {{ pointsInfo.remainPoints }}积分</text>
      </view>
    </view>

    <!-- 奖励图片列表 -->
    <view class="section">
      <view class="section-header">
        <text class="title">我的奖励</text>
        <text class="count">共{{ total }}张</text>
      </view>
      
      <scroll-view 
        class="image-list"
        scroll-y
        @scrolltolower="loadMore"
        :refresher-enabled="true"
        :refresher-triggered="isRefreshing"
        @refresherrefresh="onRefresh"
      >
        <view class="image-grid">
          <view 
            v-for="item in imageList" 
            :key="item.id"
            class="image-item"
          >
            <image 
              :src="item.imageUrl" 
              mode="aspectFill"
              @click="previewImage(item.imageUrl)"
            />
            <view class="image-footer">
              <text class="date">{{ formatDate(item.createdAt, 'MM-DD') }}</text>
              <view class="actions">
                <button class="action-btn" @click="handleShare(item)">
                  <text class="iconfont icon-share"></text>
                </button>
                <button class="action-btn" @click="handleDelete(item)">
                  <text class="iconfont icon-delete"></text>
                </button>
              </view>
            </view>
          </view>
        </view>

        <!-- 加载状态 -->
        <view v-if="loading" class="loading">
          <text class="iconfont icon-loading"></text>
          加载中...
        </view>
        <view v-if="!loading && !hasMore" class="no-more">
          没有更多记录了
        </view>
      </scroll-view>
    </view>

    <!-- 生成按钮 -->
    <view class="generate-btn-wrapper">
      <button class="generate-btn" @click="handleGenerate">
        <text class="iconfont icon-magic"></text>
        生成奖励图片 (50积分/次)
      </button>
    </view>

    <!-- 积分规则弹窗 -->
    <uni-popup ref="rulesPopup" type="center">
      <view class="rules-popup">
        <view class="popup-header">
          <text class="title">积分规则</text>
          <button class="close-btn" @click="closeRules">
            <text class="iconfont icon-close"></text>
          </button>
        </view>
        <view class="rules-content">
          <view class="rule-item">
            <text class="iconfont icon-star"></text>
            <text>每次生成题目 +10 积分</text>
          </view>
          <view class="rule-item">
            <text class="iconfont icon-gift"></text>
            <text>每日首次额外 +20 积分</text>
          </view>
          <view class="rule-item">
            <text class="iconfont icon-clock"></text>
            <text>每日上限 100 积分</text>
          </view>
        </view>
        <button class="confirm-btn" @click="closeRules">
          知道了
        </button>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { formatDate } from '@/utils'
import { 
  getPointsInfo, 
  generateImage, 
  getImageRecords,
  deleteImage 
} from '@/api/rewards'

// 响应式状态
const pointsInfo = ref({
  totalPoints: 0,
  todayPoints: 0,
  remainPoints: 100
})

const imageList = ref([])
const total = ref(0)
const loading = ref(false)
const hasMore = ref(true)
const isRefreshing = ref(false)
const page = ref(1)
const pageSize = ref(20)

// 获取积分信息
const getPoints = async () => {
  try {
    const data = await getPointsInfo()
    pointsInfo.value = data
  } catch (error) {
    uni.showToast({
      title: error.message || '获取积分信息失败',
      icon: 'none'
    })
  }
}

// 获取图片列表
const getImages = async (isRefresh = false) => {
  if (loading.value) return
  
  try {
    loading.value = true
    
    const params = {
      page: isRefresh ? 1 : page.value,
      size: pageSize.value
    }
    
    const { list, total: totalCount } = await getImageRecords(params)
    
    if (isRefresh) {
      imageList.value = list
      page.value = 1
    } else {
      imageList.value.push(...list)
      page.value++
    }
    
    total.value = totalCount
    hasMore.value = imageList.value.length < totalCount
  } catch (error) {
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
    isRefreshing.value = false
  }
}

// 下拉刷新
const onRefresh = async () => {
  isRefreshing.value = true
  await Promise.all([
    getPoints(),
    getImages(true)
  ])
}

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loading.value) {
    getImages()
  }
}

// 生成奖励图片
const handleGenerate = async () => {
  try {
    const { imageUrl, pointsCost, pointsBalance } = await generateImage()
    
    // 更新积分信息
    pointsInfo.value.totalPoints = pointsBalance
    
    // 刷新图片列表
    getImages(true)
    
    // 显示成功提示
    uni.showToast({
      title: '生成成功',
      icon: 'success'
    })
  } catch (error) {
    uni.showToast({
      title: error.message || '生成失败',
      icon: 'none'
    })
  }
}

// 预览图片
const previewImage = (url) => {
  uni.previewImage({
    urls: [url]
  })
}

// 分享图片
const handleShare = (item) => {
  uni.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline']
  })
}

// 删除图片
const handleDelete = (item) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这张图片吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await deleteImage(item.id)
          await getImages(true)
          
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          })
        } catch (error) {
          uni.showToast({
            title: error.message || '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 积分规则弹窗
const rulesPopup = ref(null)

const showRules = () => {
  rulesPopup.value.open()
}

const closeRules = () => {
  rulesPopup.value.close()
}

// 初始化
onMounted(() => {
  getPoints()
  getImages()
})

// 分享配置
defineExpose({
  onShareAppMessage() {
    return {
      title: '快来和我一起学习汉字吧',
      path: '/pages/index/index'
    }
  }
})
</script>

<style lang="scss" scoped>
.rewards-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding-bottom: calc(env(safe-area-inset-bottom) + 80px);
}

.nav-bar {
  height: 44px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;

  .title {
    font-size: 17px;
    font-weight: 500;
    color: #333;
  }
}

.points-card {
  margin: 60px 16px 16px;
  background: linear-gradient(135deg, #2196f3, #1976d2);
  border-radius: 12px;
  padding: 16px;
  color: #fff;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    font-size: 14px;
    opacity: 0.9;
  }

  .rules-btn {
    background: none;
    padding: 0;
    margin: 0;
    line-height: 1;
    color: #fff;
    font-size: 14px;
    opacity: 0.9;

    &::after {
      display: none;
    }

    .iconfont {
      margin-right: 4px;
    }
  }

  .points {
    font-size: 36px;
    font-weight: 500;
    text-align: center;
    margin: 20px 0;
  }

  .info {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    opacity: 0.9;
  }
}

.section {
  margin: 16px;
  background: #fff;
  border-radius: 12px;
  overflow: hidden;

  .section-header {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f0f0f0;

    .title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }

    .count {
      font-size: 12px;
      color: #999;
    }
  }
}

.image-list {
  height: calc(100vh - 300px);
}

.image-grid {
  padding: 8px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
}

.image-item {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;

  image {
    width: 100%;
    aspect-ratio: 1;
  }

  .image-footer {
    padding: 8px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .date {
      font-size: 12px;
      color: #999;
    }

    .actions {
      display: flex;
      gap: 8px;
    }

    .action-btn {
      background: none;
      padding: 0;
      margin: 0;
      line-height: 1;
      color: #999;
      font-size: 16px;

      &::after {
        display: none;
      }
    }
  }
}

.loading,
.no-more {
  text-align: center;
  padding: 16px;
  color: #999;
  font-size: 14px;

  .iconfont {
    margin-right: 4px;
    animation: rotate 1s linear infinite;
  }
}

.generate-btn-wrapper {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 16px;
  background: #fff;
  border-top: 1px solid #f0f0f0;

  .generate-btn {
    height: 44px;
    background: linear-gradient(to right, #2196f3, #1976d2);
    border-radius: 22px;
    color: #fff;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center;

    &::after {
      display: none;
    }

    .iconfont {
      margin-right: 4px;
      font-size: 16px;
    }
  }
}

.rules-popup {
  width: 280px;
  background: #fff;
  border-radius: 12px;
  overflow: hidden;

  .popup-header {
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    border-bottom: 1px solid #f0f0f0;

    .title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }

    .close-btn {
      position: absolute;
      right: 12px;
      top: 50%;
      transform: translateY(-50%);
      background: none;
      padding: 0;
      margin: 0;
      line-height: 1;
      color: #999;
      font-size: 20px;

      &::after {
        display: none;
      }
    }
  }

  .rules-content {
    padding: 16px;

    .rule-item {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      font-size: 14px;
      color: #666;

      .iconfont {
        width: 24px;
        height: 24px;
        background: rgba(33, 150, 243, 0.1);
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #2196f3;
        margin-right: 8px;
      }
    }
  }

  .confirm-btn {
    height: 44px;
    background: linear-gradient(to right, #2196f3, #1976d2);
    color: #fff;
    font-size: 14px;
    line-height: 44px;
    border-radius: 0;

    &::after {
      display: none;
    }
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style> 